/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package XMLPack;

import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

 /*
  * @author Cristina
  */
public class Save2Csv
{
    JTable table;
    String fileName;

    //constructori
    public Save2Csv()
    {
        table = null;
        fileName = null;
    }
    public Save2Csv(JTable table_, String fileName_)
    {
        table = table_;
        fileName = fileName_;
    }
    //Set-Get metods
    public void setTable(JTable table_){table = table_;}
    public JTable getTable(){return table;}

    public void setFileName(String fileName_){fileName = fileName_;}
    public String getFileName(){return fileName;}

    //alte metode, ca-s mai multe
    public void Save()
    {
        Save(table, fileName);
    }

    public void Save(JTable table_, String fileName_)
    {
        FileWriter out = null;
        try {
            TableModel model = table_.getModel();
            out = new FileWriter(fileName_);
            for (int i = 0; i < model.getColumnCount(); i++) {
                out.write("\""+model.getColumnName(i) + "\",");
            }
            out.write("\n");
            for (int i = 0; i < model.getRowCount(); i++) {
                for (int j = 0; j < model.getColumnCount(); j++) {
                    out.write("\""+model.getValueAt(i, j).toString() + "\",");
                }
                out.write("\n");
            }
            out.close();
            System.out.println("write out to: " + fileName_);
        } catch (IOException ex) {
            Logger.getLogger(Save2Csv.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(Save2Csv.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}
